package com.pie4cloud.pie.job.executor.utils;

import com.pie4cloud.pie.job.api.commons.Constant;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public abstract class DirectoryUtils {

	public  List<String> getAllBaseDirectory(String baseAddress, Date date) throws IOException {

		List<String> allBaseDirectory = new ArrayList<>();
		if(StringUtils.isBlank(baseAddress)) {
			return allBaseDirectory;
		} else {
			baseAddress = PathUtils.repalceTime(baseAddress,date);
			if (StringUtils.contains(baseAddress, Constant.GATHER_DIRECTORY_WILDCARD) ||
					(StringUtils.contains(baseAddress, "(") && StringUtils.contains(baseAddress, ")")) ||
					      (StringUtils.contains(baseAddress, "${") && StringUtils.contains(baseAddress, "}"))) {
				String[] directorySlices = StringUtils.split(baseAddress, "\\*");
				List<String> tempDirectory = new ArrayList<>();
				for (int dirIndex = 0; dirIndex < directorySlices.length;dirIndex++) {
					String directorySlice = directorySlices[dirIndex];
					if (tempDirectory.isEmpty()) {
						if(dirIndex == directorySlices.length -1) {
							tempDirectory.addAll(PathUtils.decodePathReg(directorySlice));
						}else {
							List<String> list = getTempBaseDirectory(directorySlice);
							final List<String> finalTempDirectory = new ArrayList<>();
							list.stream().forEach(temp -> finalTempDirectory.add(directorySlice+"/"+temp));
							tempDirectory.addAll(finalTempDirectory);
						}
					}else {
						List<String> sliceDirectory = new ArrayList<>();
						for (int i = 0; i < tempDirectory.size(); i++) {
							List<String> list = PathUtils.decodePathReg(tempDirectory.get(i)+directorySlice);
							for (int j = 0; j < list.size(); j++) {
								if(dirIndex == directorySlices.length -1) {
									sliceDirectory.add(list.get(i));
								}else {
									sliceDirectory.addAll(getTempBaseDirectory(list.get(j)));
								}
							}
						}
						tempDirectory = sliceDirectory;
					}
				}
				allBaseDirectory = tempDirectory;
			}
			if(allBaseDirectory.isEmpty()) {
				allBaseDirectory.add(baseAddress);
			}
			return allBaseDirectory;
		}
	}

	protected abstract List<String> getTempBaseDirectory(String path) throws IOException;
}
